<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\Note;
use think\Session;

class Top extends Controller
{
    // 初始化 防止用户未登录就访问页面
    public function _initialize()
    {
        if (!session('nodeList')) {
            return $this->error('您还未登录,请登录',url('admin/index/index'));
        }
    }
    // 推荐列表
    public function index()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $data = $this->getAllRecommend();
//        halt($data);
        return view('top/index',[
            'data' => $data
        ]);
    }

    // 取消推荐
    public function noRecommend()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        // 获取修改的id
        $data = input('put.');
        $note = Note::get($data['id']);
        $result = $note->where($data)->update(['top' => 0]);
//        $result = true;
        if ($result) {
            return true;
        } else {
            return false;
        }

    }


    // 获取所有推荐笔记
    protected function getAllRecommend()
    {
        $data = Db::field('note.id,note.title,note.type,note.create_at,note.top,type.tag_name,u.nickname')
            ->table(['2B_user_note' => 'note', '2B_note_type' => 'type', '2B_user_info' => 'u'])
            ->where('note.tags_id = type.id')
            ->where('note.uid = u.uid')
            ->where('note.top','1')
            ->order('id')
            ->paginate(10);

        return $data;
    }

    /*
     * 判断权限
     */
    public function judge($auth)
    {
        $nodeList = Session::get('nodeList');
        if (empty($nodeList)) {
            return $this->error('您的权限不足!');
        }
        if (!in_array($auth,$nodeList)) {
            return $this->error('您的权限不足!');
        }
    }
}
